package net.wangds.auth.module;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;

public enum ResourceSchemaEnum {

    /**
     * 系统.
     */
    SYSTEM,
    /**
     * 应用.
     */
    APPLICATION,
    /**
     * 模块.
     */
    MODULE,
    /**
     * 菜单.
     */
    MENU,
    /**
     * 活动/特性.
     */
    ACTIVITY,
    /**
     * 动作.
     */
    ACTION,
    /**
     * 数据.
     */
    DATA;

    static {

        forcefullyInstall((schema)-> {
            schema = schema.toLowerCase();
            if(schema.equals("menu")
                    ||schema.equals("action")
                    ||schema.equals("all")
            ) {
                return new URLStreamHandler() {
                    @Override
                    protected URLConnection openConnection(URL u) throws IOException {
                        return null;
                    }
                };
            }else{
                return null;
            }
        });
    }

    public static void forcefullyInstall(URLStreamHandlerFactory factory) {
        try {
            // Try doing it the normal way
            URL.setURLStreamHandlerFactory(factory);
        } catch (final Error e) {
            // Force it via reflection
            try {
                final Field factoryField = URL.class.getDeclaredField("factory");
                factoryField.setAccessible(true);
                factoryField.set(null, factory);
            } catch (NoSuchFieldException | IllegalAccessException e1) {
                throw new Error("Could not access factory field on URL class: {}", e);
            }
        }
    }
}
